package cn.wyd.shield.http.filter;

import cn.wyd.shield.authentication.UserAuthorization;
import cn.wyd.shield.cache.AuthUrlMapper;
import cn.wyd.shield.http.support.Url;
import cn.wyd.shield.token.jwt.JwtToken;
import cn.wyd.shield.token.jwt.exception.TokenIsChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static cn.wyd.shield.token.jwt.JwtUtil.authen;

@Component
public class AuthUrlFilter {
    private static List<Url> urls;
    @Autowired
    private UserAuthorization userAuthorization;
    @Autowired
    private AuthUrlMapper authUrlMapper;

    public void doAuth(HttpServletRequest servletRequest) throws NoSuchAlgorithmException, InvalidKeyException, TokenIsChange {
        Url url = selectUrl(servletRequest.getRequestURI(), servletRequest.getMethod());
        if (url != null && url.getAuthentication()) {
            String token = servletRequest.getHeader("auth");
            JwtToken jwtToken = authen(token);
            userAuthorization.userAuthorization(url, jwtToken);
        }
    }


    private Url selectUrl(String url, String method) {
        urls = authUrlMapper.getAll();
        for (Url item : urls) {
            Pattern p = item.getPattern();
            Matcher matcher = p.matcher(url);
            if (matcher.matches() && item.getMethod().equals(method.toLowerCase())) {
                return item;
            }
        }
        return null;
    }

}
